<?php
App::uses('AppController', 'Controller');
/**
 * Menuses Controller
 *
 * @property Menus $Menus
 */
class MenusesController extends AppController {
	public $helpers = array('FileUpload.FileUpload');
	public $components = array('FileUpload.FileUpload');

	public function beforeFilter(){
		parent::beforeFilter();
		$this->FileUpload->uploadDir('files'.DS.'upload'.DS.'images');
		$this->Auth->allow('maps');
	}
	
	public function beforeRender(){
		parent::beforeRender();
		switch($this->action){
			case 'maps':
				$this->layout = 'default';
				break;
			default:
				$this->layout = 'panel';
				break;
		}
	}

/**
 * maps method
 * 
 */
	public function maps() {
		
		$this->loadModel('Doamin');
		$this->Domain->recursive = -1;
		//$this->Menus->recursive = -1;
		
		$this->Domain->id = $this->Session->read('Config.Domain.Domain.id');
		if (!$this->Domain->exists()) {
			throw new NotFoundException(__d('menuses','Invalid doamin'));
		}
		
		$options['joins'] = array(
				array('table' => 'domains_menuses',
						'alias' => 'DomainsMenus',
						'type' => 'inner',
						'conditions' => array(
								'Menus.id = DomainsMenus.menus_id'
						)
				),
				array('table' => 'domains',
						'alias' => 'Domain',
						'type' => 'inner',
						'conditions' => array(
								'DomainsMenus.domain_id = Domain.id'
						)
				)
		);
		
		$options['order'] = array(
				'Menus.lft'
		);
		
		$options['conditions'] = array(
				'Domain.id' => $this->Session->read('Config.Domain.Domain.id'),
				'Menus.position' => 0
		);
		$menuses_one = $this->Menus->find('threaded',$options);
		
		$options['conditions'] = array(
				'Domain.id' => $this->Session->read('Config.Domain.Domain.id'),
				'Menus.position' => 1
		);
		$menuses_two = $this->Menus->find('threaded',$options);
		
		$options['conditions'] = array(
				'Domain.id' => $this->Session->read('Config.Domain.Domain.id'),
				'Menus.position' => 2
		);
		$menuses_three = $this->Menus->find('threaded',$options);
		
		$options['conditions'] = array(
				'Domain.id' => $this->Session->read('Config.Domain.Domain.id'),
				'Menus.position' => 3
		);
		$menuses_four = $this->Menus->find('threaded',$options);
		
		$options['conditions'] = array(
				'Domain.id' => $this->Session->read('Config.Domain.Domain.id'),
				'Menus.position' => 4
		);
		$menuses_five = $this->Menus->find('threaded',$options);
		
		$options['conditions'] = array(
				'Domain.id' => $this->Session->read('Config.Domain.Domain.id'),
				'Menus.position' => 5
		);
		$menuses_six = $this->Menus->find('threaded',$options);
		
		$this->set(compact('domain','menuses_one','menuses_two','menuses_three','menuses_four','menuses_five','menuses_six'));
		
	}

/**
 * index method
 *
 * @return void
 */
	public function index() {
		
		$this->loadModel('Article');		
		$this->loadModel('Doamin');
		
		$this->Domain->recursive = -1;
		$this->Menus->recursive = -1;
		
		$options['conditions'] = array('Article.domain_id'=>$this->Session->read('Config.Domain.Domain.id'),'Article.status'=>1);
		$articles_ = $this->Article->find('all',$options);
		if(is_array($articles_)){
			foreach ($articles_ as $key => $article) {
				$articles[$article['Article']['menuses_id']][$article['Article']['id']] = array('name'=>$article['Article']['name'],'id'=>$article['Article']['id'],'description'=>$article['Article']['descriptions']);
			}
		}
		
		
		$this->Domain->id = $this->Session->read('Config.Domain.Domain.id');
		if (!$this->Domain->exists()) {
			throw new NotFoundException(__d('menuses','Invalid doamin'));
		}
		
		
		$options['joins'] = array(
		    array('table' => 'domains_menuses',
		        'alias' => 'DomainsMenus',
		        'type' => 'inner',
		        'conditions' => array(
		            'Menus.id = DomainsMenus.menus_id'
		        )
		    ),
		    array('table' => 'domains',
		        'alias' => 'Domain',
		        'type' => 'inner',
		        'conditions' => array(
		            'DomainsMenus.domain_id = Domain.id'
		        )
		    )
		);
		
		$options['conditions'] = array(
		    'Domain.id' => $this->Session->read('Config.Domain.Domain.id')
		);
		$options['order'] = array(
				   'Menus.lft'
		);
		
		$menuses = $this->Menus->find('threaded',$options);
		$menuses = $this->treeForCombobox($menuses,'Menus',array('model'=>'Menus','name'=>'name'),false);
		$menuses_combobox = $menuses;		
	
		$options['fields'] = array('Menus.id','Menus.status');
		$statuses = $this->Menus->find('list',$options);
		
		$options['fields'] = array('Menus.id','Menus.position');
		$positions = $this->Menus->find('list',$options);
		
			
		if(is_array($menuses)){
			foreach ($menuses as $key => $name) {
				$article = (isset($articles[$key])) ? $articles[$key] : null;  
				$menuses[$key] = array('id'=>$key,'name'=>$name,'status'=>$statuses[$key],'position'=>$positions[$key],'article'=>$article);
			}
		}
		
		$menu_positions = Configure::read('Config.menu_positions');
		$setting_groups = Configure::read('Config.cfg_groups');
		$this->set(compact('domain','menuses','menuses_combobox','menu_positions','setting_groups'));
		
	}

/**
 * view method
 *
 * @param string $id
 * @return void
 */
	public function view($id = null) {
		$this->Menus->id = $id;
		if (!$this->Menus->exists()) {
			throw new NotFoundException(__d('menuses','Invalid menus'));
		}
		$this->set('menus', $this->Menus->read(null, $id));
	}

/**
 * add method
 *
 * @return void
 */
	public function add() {
		if ($this->request->is('post')) {
// 			debug($this->request->data); die;
			$this->request->data['Menus']['slug'] = strtolower(Inflector::slug($this->request->data['Menus']['name'],'-'));
			
			if($this->FileUpload->success){
				$this->request->data['Menus']['upload_id'] = $this->Menus->Upload->getLastInsertID();
			}else{
				// 				throw new NotFoundException($this->FileUpload->showErrors());
			}
				
			$this->Menus->set($this->request->data);
			if ($this->Menus->validates()) {
				$this->Menus->create();
				if ($this->Menus->save($this->request->data)) {
					$this->Session->setFlash(__d('menuses','The menus has been saved'));
					
	// 				if($this->request->data['Menus']['parent_id'] == null || $this->request->data['Menus']['parent_id'] == ''){
	// 					$this->loadModel('Configuration');
	// 					$data['Configuration']['name'] = $this->request->data['Menus']['slug'];
	// 					$data['Configuration']['cfg_group_id'] = 5;
	// 					$data['Configuration']['domain_id'] = $this->request->data['Domain']['Domain'][0];
	// 					$data['Configuration']['value'] = 'null';
	// 					$this->Configuration->create();
	// 					if($this->Configuration->save($data)){
	// 					}else{
	// 						throw new NotFoundException(__d('menuses','Invalid Configuration for menu'));
	// 					}
	// 				}
					
					if(isset($this->passedArgs['d']) && !empty($this->passedArgs['d'])) $this->redirect(array('controller'=>'domains','action' =>'view',$this->passedArgs['d'],'d'=>'menus'));
					$this->redirect(array('action' => 'index'));
				} else {
					$this->Session->setFlash(__d('menuses','The menus could not be saved. Please, try again.'));
				}
			}else{
				$this->Session->setFlash(__d('menuses','The menus could not be saved. Please, try again.'));
			}
		}
		
			// dodajemy do domeny
			$this->Menus->Domain->id = $this->Session->read('Config.Domain.Domain.id');
			if ($this->Menus->Domain->exists()) {
				$data['Domain']['Domain'][0] = $this->Session->read('Config.Domain.Domain.id');
				$this->request->data = $data;
			}
		
		if(isset($this->passedArgs['pi']) && !empty($this->passedArgs['pi'])){
			// dodajemy do domeny
			$this->Menus->id = $this->passedArgs['pi'];
			if ($this->Menus->exists()) {
				$data['Menus']['parent_id'] = $this->passedArgs['pi'];
				$this->request->data = $data;
			}
		}
		
		$domains = $this->Menus->Domain->find('list');
		
		$options['joins'] = array(
		    array('table' => 'domains_menuses',
		        'alias' => 'DomainsMenus',
		        'type' => 'inner',
		        'conditions' => array(
		            'Menus.id = DomainsMenus.menus_id'
		        )
		    ),
		    array('table' => 'domains',
		        'alias' => 'Domain',
		        'type' => 'inner',
		        'conditions' => array(
		            'DomainsMenus.domain_id = Domain.id'
		        )
		    )
		);
		$options['conditions'] = array(
		    'Domain.id' => $this->Session->read('Config.Domain.Domain.id')
		);
		
		$parentMenuses = $this->Menus->find('threaded',$options);
		$parentMenuses = $this->treeForCombobox($parentMenuses,'Menus',array('model'=>'Menus','name'=>'name'),false);
		
		$menu_positions = Configure::read('Config.menu_positions');
		
		//$submenus = $this->Menus->Submenu->find('list');
		$this->set(compact('parentMenuses', 'domains','menu_positions'));
	}

/**
 * edit method
 *
 * @param string $id
 * @return void
 */
	public function edit($id = null) {
		$this->Menus->id = $id;
		if (!$this->Menus->exists()) {
			throw new NotFoundException(__d('menuses','Invalid menus'));
		}
		if ($this->request->is('post') || $this->request->is('put')) {
			if($this->FileUpload->success){
				$this->request->data['Menus']['upload_id'] = $this->Menus->Upload->getLastInsertID();
			}else{
// 				throw new NotFoundException($this->FileUpload->showErrors());
			}
			
			if(!isset($this->request->data['Menus']['title']) || empty($this->request->data['Menus']['title'])){
				$this->request->data['Menus']['title'] = $this->request->data['Menus']['name'];
			}

			if(!isset($this->request->data['Menus']['description']) || empty($this->request->data['Menus']['description'])){
				$this->request->data['Menus']['description'] = $this->request->data['Menus']['name'];
			}
			
			if(!isset($this->request->data['Menus']['slug']) || empty($this->request->data['Menus']['slug'])) 
				$this->request->data['Menus']['slug'] = strtolower(Inflector::slug($this->request->data['Menus']['name'],'-'));
			if ($this->Menus->save($this->request->data)) {
				$this->Session->setFlash(__d('menuses','The menus has been saved'));
					


// 				debug($this->request->data); die;
				if(isset($this->request->data['Article']['Article']) && !empty($this->request->data['Article']['Article'])){
					$this->loadModel('Article');
					$menus_id = (int)$this->request->data['Menus']['id'];
					if($this->Article->updateAll(array('Article.menuses_id'=>$menus_id),array('Article.id'=>$this->request->data['Article']['Article']))){
						
					}
				}				
				
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__d('menuses','The menus could not be saved. Please, try again.'));
			}
		} else {
			$this->request->data = $this->Menus->read(null, $id);
		}
		$this->Menus->Domain->id = $this->Session->read('Domain.Domain.id');
		if ($this->Menus->Domain->exists()) {
			$this->request->data['Domain']['domain_id'] = $this->Session->read('Domain.Domain.id');
		}
		
		$options['joins'] = array(
		    array('table' => 'domains_menuses',
		        'alias' => 'DomainsMenus',
		        'type' => 'inner',
		        'conditions' => array(
		            'Menus.id = DomainsMenus.menus_id'
		        )
		    ),
		    array('table' => 'domains',
		        'alias' => 'Domain',
		        'type' => 'inner',
		        'conditions' => array(
		            'DomainsMenus.domain_id = Domain.id'
		        )
		    )
		);
		$options['conditions'] = array(
		    'Domain.id' => $this->Session->read('Config.Domain.Domain.id')
		);
		
		$parentMenuses = $this->Menus->find('threaded',$options);
		$parentMenuses = $this->treeForCombobox($parentMenuses,'Menus',array('model'=>'Menus','name'=>'name'),false);
		
		$domains = $this->Menus->Domain->find('list');
		$this->loadModel('Article');
		$options = array();
		$options['conditions'] = array(
				'Article.domain_id' => $this->Session->read('Domain.Domain.id')
		);
		$articles = $this->Article->find('list',$options);
		
		$options = array();
		$options['conditions'] = array(
				'Article.domain_id' => $this->Session->read('Domain.Domain.id'),
				'Article.menuses_id' => $id,
		);
		$options['fields'] = array('Article.id');
		$articles_selected = $this->Article->find('list',$options);
		$menu_positions = Configure::read('Config.menu_positions');
		
		$this->set(compact('parentMenuses', 'domains','menu_positions','articles','articles_selected'));
	}

/**
 * delete method
 *
 * @param string $id
 * @return void
 */
	public function delete($id = null) {
		if (!$this->request->is('post')) {
			throw new MethodNotAllowedException();
		}
		$this->Menus->id = $id;
		if (!$this->Menus->exists()) {
			throw new NotFoundException(__d('menuses','Invalid menus'));
		}
		if ($this->Menus->delete()) {			
			
			$this->Session->setFlash(__d('menuses','Menus deleted'));
			if(isset($this->passedArgs['d']) && !empty($this->passedArgs['d'])) $this->redirect(array('controller'=>'domains','action' =>'view',$this->passedArgs['d'],'d'=>'menus'));
			$this->redirect(array('action' => 'index'));
		}
		$this->Session->setFlash(__d('menuses','Menus was not deleted'));
		if(isset($this->passedArgs['d']) && !empty($this->passedArgs['d'])) $this->redirect(array('controller'=>'domains','action' =>'view',$this->passedArgs['d'],'d'=>'menus'));
		$this->redirect(array('action' => 'index'));
	}
	

/**
 * 
 * Move up menu position
 * @param unknown_type $id
 * @param unknown_type $delta
 */	
	function up($id = null, $delta = null){
		$this->autoRender = false;
		
		if (!$this->request->is('post')) {
			throw new MethodNotAllowedException();
		}
		$this->Menus->id = $id;
		if (!$this->Menus->exists()) {
			throw new NotFoundException(__d('menuses','Invalid menus'));
		}

		if ($delta > 0) {
			$return = $this->Menus->moveUp($this->Menus->id, abs($delta));
		} else {
			$this->Session->setFlash('Please provide a number of positions the category should be moved up.');
		}		
		$this->redirect(array('action' => 'index'), null, true);
	
	}
	
	function down($id = null, $delta = null) {
		$this->autoRender = false;
		
		if (!$this->request->is('post')) {
			throw new MethodNotAllowedException();
		}
		$this->Menus->id = $id;
		if (!$this->Menus->exists()) {
			throw new NotFoundException(__d('menuses','Invalid menus'));
		}
	
		if ($delta > 0) {
			$this->Menus->moveDown($this->Menus->id, abs($delta));
		} else {
			$this->Session->setFlash('Please provide the number of positions the field should be moved down.');
		}		
		$this->redirect(array('action' => 'index'), null, true);
	}
	
	function reorder() {
		$this->Menus->reorder();
		$this->redirect(array('action' => 'index'), null, true);
	}
}
